/**
 * Created by zhouli on 19/6/25
 * Email li.zhou@huilianyi.com
 * 岗位信息
 * 这个地方逻辑比较特殊
 * 编辑岗位信息，要设置岗位先删除，然后新增
 */
import React from 'react';
import {connect} from 'react-redux';
import {deepFullCopy, messages} from "share/common";
import 'styles/enterprise-manage/person-manage/person-detail/person-detail-components/position-info.scss';
import {Button, Table, message, Select, Tooltip, Switch, Input, Icon, Modal, Form, Popover} from 'antd';
import {positionInfoModel} from 'containers/enterprise-manage/person-manage/person-detail/person-detail.model';
import Chooser from 'components/chooser';
import antdc from 'share/prototype-extend/antd-common';
import configureStore from "stores/index";
import {setEnableDepCompany} from "actions/setting";
import OrgService from 'containers/enterprise-manage/org-structure/org-structure.service';

const FormItem = Form.Item;
const confirm = Modal.confirm;

class PositionInfo extends React.Component {
  constructor(props) {
    super(props);
    this.willEdit = null;
    this.state = {
      company: {},//如果部门关联了公司，需要用这个查询部门
      isEnableDepCompany: "INIT",//部门是否关联公司
      userJobsDTO: deepFullCopy(positionInfoModel),
      userJobsDTOs: [],
      loading: false,
      modalKey: 0,
      showCreatModel: false,
      columns: [
        {
          title: messages('enterprise-manage.key313'/*公司*/),
          key: "companyName",
          dataIndex: 'companyName',
          render: text => antdc.renderPopover(text)
        },
        {
          title: messages('enterprise-manage.key318'/*部门*/),
          key: "departmentName",
          dataIndex: 'departmentName',
          render: (text, record) => this.renderPopover(text, record)
        },
        {
          title: messages('enterprise-manage.key238')/*职位*/,
          key: "position",
          dataIndex: 'position',
          render: text => antdc.renderPopover(text)
        },
        {
          title: messages('enterprise-manage.key237')/*职务*/,
          key: "duty",
          dataIndex: 'duty',
          render: text => antdc.renderPopover(text)
        },

        {
          title: messages('enterprise-manage.key240')/*级别*/,
          key: "rank",
          dataIndex: 'rank',
          render: text => antdc.renderPopover(text)
        },
        {
          title: messages('enterprise-manage.key372')/*主岗*/,
          key: "companyMainPosition",
          dataIndex: 'companyMainPosition',
          render: (text, record) => {
            return <Switch checked={record.companyMainPosition}
                           disabled={!this.props.isEdit}
                           checkedChildren={messages('enterprise-manage.key372')/*主岗*/}
                           onChange={(val) => {
                             this.onCompanyMainPositionChange(val, record)
                           }}/>
          }
        },
        {
          title: messages('enterprise-manage.key321'/*操作*/),
          dataIndex: "id",
          key: "id",
          render: (text, record) => {
            if (this.props.isEdit) {
              return (
                <span>
                   <span><a onClick={(e) => this.deletePosition(e, record)}>{messages('common.delete')/*删除*/}</a></span>
                  &nbsp;&nbsp;
                  <span><a onClick={(e) => this.editPosition(e, record)}>{messages('common.edit')/*编辑*/}</a></span>
                </span>
              )
            }
          }
        }
      ],
    }
  }

  componentDidMount() {
    const {userJobsDTOs} = this.props;
    this.setState({
      userJobsDTOs: userJobsDTOs ? userJobsDTOs : []
    })
    this.props.onRef && this.props.onRef(this);
    this.checkEnableDepCompany();

  }

  //检测部门是否关联公司
  checkEnableDepCompany = () => {
    OrgService.checkEnableDepCompany()
      .then(res => {
        configureStore.store.dispatch(setEnableDepCompany(res.data.companyControlStatus));
        this.setState({
          isEnableDepCompany: res.data.companyControlStatus
        })
      })
  };
  refreshPositionInfo = (userJobsDTOs) => {
    //过滤调删除了的
    this.setState({
      userJobsDTOs: userJobsDTOs.filter(item => {
        return !item.deleted
      })
    })
  };

  renderPopover = (text, record) => {
    return (
      <span>
        {text ? <Popover placement="topLeft" content={record.departmentPath} overlayStyle={{maxWidth: 500}}>{text}</Popover> : '-'}
      </span>
    );
  };

  //设置为主岗
  onCompanyMainPositionChange = (val, record) => {
    let {userJobsDTOs} = this.state;
    /*
    * 校验逻辑（产品设计）
    * 1.同一个公司只能有一个主岗，设置一个公司主岗，则同公司另一个岗位自动变为非主岗
    * 2.岗位不能手动把主岗设置为非主岗
    * */
    if (!val) {
      message.warn(messages('enterprise-manage.key373')/*不能手动把主岗设置为非主岗,你可以直接添加一个主岗*/);
      return
    }
    if (val) {
      userJobsDTOs.map(item => {
        if (item.companyId === record.companyId) {
          item.companyMainPosition = false;
        }
      });
      record.companyMainPosition = val;
      this.props.userJobsDTOChange(userJobsDTOs)
    }
  };
  editPosition = (e, record) => {
    this.willEdit = deepFullCopy(record);
    //如果点击取消需要还原
    this.newPosition(this.willEdit);
  };
  //删除职位
  deletePosition = (e, record) => {
    let {userJobsDTOs} = this.state;
    let _this = this;
    confirm({
      title: messages('enterprise-manage.key384')/*确认*/,
      content: messages('enterprise-manage.key385')/*你确认删除该岗位吗？*/,
      onOk() {
        record.deleted = true;
        _this.props.userJobsDTOChange(userJobsDTOs, record)
      },
      onCancel() {

      },
    });
  };
  //新增职位
  newPosition = (position) => {
    let {modalKey} = this.state;
    modalKey++;
    this.setState({
      company: position && position.companyId ? position : deepFullCopy(positionInfoModel),
      userJobsDTO: position && position.companyId ? position : deepFullCopy(positionInfoModel),
      modalKey,
    }, () => {
      this.setState({
        showCreatModel: true
      })
    })
  }
  //取消新增
  cancelNew = () => {
    this.willEdit = null;
    this.setState({
      showCreatModel: false
    })
  }
  checkSomeUni_id = (uni_id, userJobsDTOs) => {
    let len = userJobsDTOs.length;
    for (let i = 0; i < len; i++) {
      let id = userJobsDTOs[i].companyId + userJobsDTOs[i].departmentId + userJobsDTOs[i].position
      if (id === uni_id) {
        return true
      }
    }
  }
  /*
  * 检查是不是有相同的公司，把公司设置为非主岗位
  * @newPosition 新职位
  * @userJobsDTOs 职位列表
  * */
  checkHasCompanySetCompanyMainPosition = (newPosition, userJobsDTOs) => {
    let len = userJobsDTOs.length;
    for (let i = 0; i < len; i++) {
      let item = userJobsDTOs[i];
      if (!item.deleted) {
        if (item.companyId === newPosition.companyId && item.companyMainPosition) {
          //如果存在相同公司，且存在的公司是主岗，则新加的公司为 非主岗
          newPosition.companyMainPosition = false;
          return userJobsDTOs;//主岗 只要坚持到一个就可以了
        } else if (item.companyId === newPosition.companyId && !item.companyMainPosition) {
          //如果存在相同公司，且存在的公司是主岗，则新加的公司为 主岗
          newPosition.companyMainPosition = true;
        }
      }
    }
    return userJobsDTOs
  }
  deletePostionById = (postionList, id) => {
    return postionList.filter(item => item.id !== id);
  };
  //点击保存
  handleSave = (e) => {
    let {userJobsDTOs,} = this.state;
    let _userJobsDTO = this.state.userJobsDTO;
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (this.willEdit) {
          /*
          * 如果是编辑，需要编辑的数据从源列表中删除
          * 但是需要保留序号，因为接口要求编辑一条数据，他的顺序不能变
          * */
          values.id = this.willEdit.id;
          this.willEditIndex = this.willEdit._index;
          userJobsDTOs = this.deletePostionById(userJobsDTOs, this.willEdit.id);
          this.willEdit = null;
        }

        let userJobsDTO = Object.assign(_userJobsDTO, {
          companyId: values.company[0] ? values.company[0].id : positionInfoModel.companyId,
          companyName: values.company[0] ? values.company[0].companyName : positionInfoModel.companyName,
          // departmentId: values.department[0] ? values.department[0].departmentId : positionInfoModel.departmentId,
          // departmentName: values.department[0] ? values.department[0].name : positionInfoModel.departmentName,
          duty: values.duty[0] ? values.duty[0].messageKey : positionInfoModel.duty,
          dutyCode: values.duty[0] ? values.duty[0].value : positionInfoModel.dutyCode,
          rank: values.rank[0] ? values.rank[0].messageKey : positionInfoModel.rank,
          rankCode: values.rank[0] ? values.rank[0].value : positionInfoModel.rankCode,
          position: values.position,
          id: values.id,
        });
        if(this.state.isEnableDepCompany !== "OPEN"){
          userJobsDTO.departmentName = values.department[0] ? values.department[0].name : positionInfoModel.departmentName
          userJobsDTO.departmentId = values.department[0] ? values.department[0].departmentId : positionInfoModel.departmentId
        }
        if(this.state.isEnableDepCompany === "OPEN" && !userJobsDTO.departmentId){
          message.warn(messages('enterprise-manage.key404')/*部门必须选择*/);
          return;
        }
        let uni_id = userJobsDTO.companyId + userJobsDTO.departmentId + userJobsDTO.position;
        if (this.checkSomeUni_id(uni_id, userJobsDTOs)) {
          message.warn(messages('enterprise-manage.key386')/*已经存在相同的岗位信息，请重新添加*/);
          return
        }
        userJobsDTO.uni_id = uni_id;
        userJobsDTOs = this.checkHasCompanySetCompanyMainPosition(userJobsDTO, userJobsDTOs);
        if (userJobsDTO.id) {
          userJobsDTO.modified = true;
        }
        if (this.willEditIndex === 0 || this.willEditIndex) {
          //编辑
          userJobsDTO._index = this.willEditIndex;
          userJobsDTOs.splice(this.willEditIndex, 0, userJobsDTO);
          this.willEditIndex = null;
        } else {
          //新增
          userJobsDTOs.push(userJobsDTO);
        }
        this.props.userJobsDTOChange(userJobsDTOs);
        this.setState({
          showCreatModel: false
        })
      }
    });
  };

  handleFormChange = () => {

  }
  handleChange = (val) => {
    this.setState({
      loading: false
    })
  };
  handleChangeCom = (val) => {
    let userJobsDTO = this.state.userJobsDTO;
    if(this.state.isEnableDepCompany === "OPEN"){
      if(val && val[0] && val[0].companyOID){
        if(val[0].companyOID !== userJobsDTO.companyOID){
          //选择的公司不一样，需要清空
          userJobsDTO.departmentName = null;
          userJobsDTO.departmentId = null;
        }
        this.setState({
          userJobsDTO,
          company: val[0] ? val[0] : {},
          loading: false
        },()=>{
          console.log(userJobsDTO)
        })
      }
    }else {
      this.setState({
        loading: false
      })
    }
  };
  handleChangeDep = (val) => {
    if(this.state.isEnableDepCompany === "OPEN"){
      let userJobsDTO = this.state.userJobsDTO;
      if(val && val[0] && val[0].departmentId){
        userJobsDTO.departmentName = val[0].name;
        userJobsDTO.departmentId = val[0].departmentId;
      }else {
        userJobsDTO.departmentName = null;
        userJobsDTO.departmentId = null;
      }
      this.setState({
        userJobsDTO,
        loading: false
      })
    }else {
      this.setState({
        loading: false
      })
    }
  };

  render() {
    let {userJobsDTO, modalKey, loading, userJobsDTOs, columns, showCreatModel, isEnableDepCompany, company} = this.state;
    const {isEdit} = this.props;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14, offset: 1},
    };
    const {getFieldDecorator} = this.props.form;
    let nameTips = (
      <div>
        <p>{messages('enterprise-manage.key374')/*1.岗位同一个公司 有且只能有一个主岗位*/} </p>
        <p>{messages('enterprise-manage.key375')/*2.可以在不同公司担任多个岗位*/}</p>
      </div>
    );
    return (
      <div className="position-info-wrap">
        <div className='title-wrap'>
          <div className='title'>{messages('enterprise-manage.key376')/*岗位信息*/}</div>
          <div className='new'>
            {isEdit &&
            <Button type='primary' onClick={this.newPosition}>{messages('enterprise-manage.key377')/*新增*/}</Button>}
            <span className="tips-wrap">
                    <Tooltip title={nameTips}>
                    {/*中文名可以不填写，直接写在姓里面*/}
                      <Icon type="question-circle"/>
                    </Tooltip>
                  </span>
          </div>
          <div className='clear'/>
        </div>
        <div>
          {/* uni_id 前端生成一个唯一标志 用 公司id+部门id+职位 */}
          <Table
            loading={loading}
            dataSource={userJobsDTOs}
            columns={columns}
            size="middle"
            rowKey={'uni_id'}
            bordered={true}
          />
        </div>
        <Modal
          key={modalKey}
          closable
          className='position-info-modal'
          width={600}
          title={messages('enterprise-manage.key378')/*新增岗位*/}
          visible={showCreatModel}
          footer={null}
          onCancel={this.cancelNew}
          destroyOnClose={true}
        >
          <Form onSubmit={this.handleSave} onChange={this.handleFormChange}>
            <FormItem {...formItemLayout}
                      label={messages('enterprise-manage.key313')/*公司*/}
            >
              {getFieldDecorator('company', {
                initialValue: userJobsDTO.companyId ? [
                  {
                    companyName: userJobsDTO.companyName,
                    companyOID: userJobsDTO.companyOID,
                    id: userJobsDTO.companyId
                  }
                ] : [],
                rules: [
                  {
                    required: true,
                    message: messages("common.please.select")
                  },
                ]
              })(
                <Chooser single={true}
                         type="all_company_with_legal_entity"
                         labelKey="companyName"
                         valueKey="id"
                         onChange={this.handleChangeCom}
                         listExtraParams={{}}/>
              )
              }
            </FormItem>
            {isEnableDepCompany === "OPEN" &&
            <FormItem {...formItemLayout}
                      label={<span><span className='required-red'>*&nbsp;</span>
              <span>{messages('enterprise-manage.key318')/*部门*/}</span></span>}
            >
              {getFieldDecorator('department', {
              })(
                 <div>
                   <Chooser single={true}
                            type="department"
                            labelKey="name"
                            value={company.companyName && userJobsDTO.departmentId ? [
                              {
                                name: userJobsDTO.departmentName,
                                departmentId: userJobsDTO.departmentId
                              }
                            ] : []}
                            disabled={!company.companyName}
                            valueKey="departmentId"
                            onChange={this.handleChangeDep}
                            listExtraParams={{
                              companyOID: company.companyOID
                            }}/>
                 </div>
              )
              }
            </FormItem>}

            {isEnableDepCompany !== "OPEN" &&  <FormItem {...formItemLayout}
                                                         label={messages('enterprise-manage.key318')/*部门*/}
            >
              {getFieldDecorator('department', {
                initialValue: userJobsDTO.departmentId ? [
                  {
                    name: userJobsDTO.departmentName,
                    departmentId: userJobsDTO.departmentId
                  }
                ] : [],
                rules: [
                  {
                    required: true,
                    message: messages("common.please.select")
                  },
                ]
              })(
                <Chooser single={true}
                         type="department"
                         labelKey="name"
                         valueKey="departmentId"
                         onChange={this.handleChange}
                         listExtraParams={{}}/>
              )
              }
            </FormItem>}

            <FormItem {...formItemLayout}
                      label={messages('enterprise-manage.key238')/*职位*/}
            >
              {getFieldDecorator('position', {
                initialValue: userJobsDTO.position,
                rules: [
                  {
                    required: true,
                    message: messages("common.please.enter")
                  },
                ],
              })(
                <Input placeholder={messages("common.please.enter")}/>
              )}
            </FormItem>
            <FormItem {...formItemLayout}
                      label={messages('enterprise-manage.key237')/*职务*/}
            >
              {getFieldDecorator('duty', {
                initialValue: userJobsDTO.duty ? [
                  {
                    value: userJobsDTO.dutyCode,
                    messageKey: userJobsDTO.duty
                  }
                ] : [],
                rules: []
              })(
                <Chooser single={true}
                         type="personDutyModel"
                         labelKey="messageKey"
                         valueKey="value"
                         onChange={this.handleChange}
                         placeholder={messages("common.please.select")}
                         listExtraParams={{systemCustomEnumerationType: "1002"}}/>
              )}
            </FormItem>

            <FormItem {...formItemLayout}
                      label={messages('enterprise-manage.key240')/*级别*/}
            >
              {getFieldDecorator('rank', {
                initialValue: userJobsDTO.rank ? [
                  {
                    value: userJobsDTO.rankCode,
                    messageKey: userJobsDTO.rank
                  }
                ] : [],
                rules: []
              })(
                <Chooser single={true}
                         type="personRankModel"
                         labelKey="messageKey"
                         valueKey="value"
                         onChange={this.handleChange}
                         placeholder={messages("common.please.select")}
                         listExtraParams={{systemCustomEnumerationType: "1008"}}/>
              )}
            </FormItem>
            <div className="role-list-from-footer">
              <Button onClick={this.cancelNew}>
                {messages("common.cancel")}
              </Button>
              &nbsp;&nbsp;&nbsp;
              <Button type="primary"
                      htmlType="submit"
                      disabled={loading}>
                {messages("common.save")}
              </Button>
            </div>
          </Form>

        </Modal>

      </div>
    )
  }
}

PositionInfo.propTypes = {
  userJobsDTOChange: React.PropTypes.any,//职位信息改变时
  isEdit: React.PropTypes.any,//设置显示
  userJobsDTO: React.PropTypes.any//职位信息
};
PositionInfo.defaultProps = {
  originEditingStatus: false,
};

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    isOldCompany: state.login.isOldCompany,
  }
}

const WrappedPositionInfo = Form.create()(PositionInfo);
export default connect(mapStateToProps)(WrappedPositionInfo);
